package com.heima.controller;

import com.heima.pojo.Article;
import com.heima.pojo.Category;
import com.heima.pojo.PageBean;
import com.heima.pojo.Result;
import com.heima.service.ArticleService;
import com.heima.utils.JwtUtil;
import com.heima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/*
本类存储所有文章数据
先 获取令牌 校验令牌：true 放行 | false 报401
下一步：写拦截器
 */

@RestController
@RequestMapping("/article")
@Validated
//@CrossOrigin
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /*//localhost:8080/article/list
    @GetMapping("/list")
    public Result<String> list(*//*@RequestHeader(name = "Authorization") String token, HttpServletResponse response*//*){
        //验证token
        *//*try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            return Result.success("所有的文章数据");
        } catch (Exception e) {
            //http响应状态码 401
            response.setStatus(401);
            return Result.error("未登录");
        }*//*
        return Result.success("所有的文章数据");
    }*/

    @PostMapping
    public Result add(@RequestBody @Validated(Article.Add.class) Article article){
        articleService.add(article);
        return Result.success();
    }

    @GetMapping
    public Result<PageBean<Article>>list(Integer pageNum,//当前页码 (1-m)
                                         Integer pageSize,//每页条数
                                         //@RequestParam: 指定后面的参数不是必须的
                                         @RequestParam(required = false)Integer categoryId,//文章分类ID
                                         @RequestParam(required = false)String state){//发布状态
        PageBean<Article> pb = articleService.list(pageNum,pageSize,categoryId,state);

        return Result.success(pb);
    }


    @GetMapping("/detail")
    public Result<Article> detail(Integer id){
        Article a = articleService.findById(id);
        return Result.success(a);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(Article.Update.class) Article article){
        articleService.update(article);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Integer id){
        articleService.delete(id);
        return Result.success();
    }


}
